package com.usian.service;

import com.usian.pojo.TbItem;
import com.usian.redis.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class CartService {
    @Autowired
    private RedisClient redisClient;

    @Value("${CART_REDIS_NAME}")
    private String CART_REDIS_NAME;

    /**
     * 根据用户 ID 查询用户购物车
     */
    public Map<String, TbItem> selectCartByUserId(String userId) {
        return (Map<String, TbItem>) redisClient.hget(CART_REDIS_NAME,userId);
    }

    /**
     * 缓存购物车
     *
     * @param cart
     */

    public Boolean insertCart(String userId, Map<String, TbItem> cart) {
        return redisClient.hset(CART_REDIS_NAME, userId, cart);
    }

    public List<TbItem> getCarts(String[] ids, String userId) {
        //获取当前用户的所有购物车数据
        Map<String,TbItem> map = (Map<String,TbItem>) redisClient.hget(CART_REDIS_NAME, userId);

        List<TbItem> list = new ArrayList<>();
        //根据订单id，依次从map中查询对应的商品信息
        for (String id : ids) {
            list.add(map.get(id));
        }
        return list;
    }
}
